package com.tz.farmer.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smartPark.msframe.result.ResultEx;
import com.tz.farmer.enums.ErrorCodeEnum;
import com.tz.farmer.model.GoodsInfo;
import com.tz.farmer.model.VisitRecords;
import com.tz.farmer.service.BusinessService;
import com.tz.farmer.service.GoodsInfoService;
import com.tz.farmer.service.VisitRecordsService;
import com.tz.farmer.so.BusinessPushSo;
import com.tz.farmer.util.AppSecretConfig;
import com.tz.farmer.util.ResultExM;
import io.swagger.annotations.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.servlet.http.HttpServletResponse;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @description: 商户/商品（h5）
 * @name BusinessController
 * @author: xhj
 * @date: 2021/6/23
 * @version V1.0
 */
@RestController
@RequestMapping("push")
@Api(value = "商户/商品（h5）", tags = "商户/商品（h5）控制器")
public class BusinessController {

    private static Logger logger = LoggerFactory.getLogger(BusinessController.class);

    @Resource
    BusinessService businessService;

    @Resource
    GoodsInfoService goodsInfoService;

    @Resource
    VisitRecordsService visitRecordsService;

    @Resource
    RestTemplate restTemplate;

    @Resource
    JdbcTemplate jdbcTemplate;

    public String addZhuCe(String uniscId,String property,String phone) throws Exception {
        String body = "";
        Long now = System.currentTimeMillis(); //请求时间
        String sign = "appid=" + AppSecretConfig.appid + "&appsecret=" + AppSecretConfig.appSecret + "&time=" + now;
        System.out.println(sign);
        sign = encrypt(sign, AppSecretConfig.publicKey);//公钥加密 接口提供方提供公钥
        System.out.println(sign);
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(AppSecretConfig.url);
        CloseableHttpClient httpCilent = HttpClients.createDefault();
        httpPost.setHeader("signature", sign);
        httpPost.setHeader("appid", AppSecretConfig.appid);
        JSONObject obj1 = new JSONObject();
        Map resultMap = new HashMap();
        JSONArray arr = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("uniscid", uniscId);
        obj.put("companyFlag", property);
        obj.put("legalPhone", phone);
        arr.add(obj);
        obj1.put("sourceUniscid", AppSecretConfig.sourceUniscid);
        obj1.put("data", arr);
        StringEntity se = new StringEntity(obj1.toJSONString(), "UTF-8");
        se.setContentType("application/json");
        httpPost.setEntity(se);
        // 发起请求
        CloseableHttpResponse response = httpCilent.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            resultMap.put("status", "success");
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity);//响应结果
            }

        } else {
            throw new RuntimeException("调用失败");
        }
        if (response != null) {
            response.close();
        }
        httpCilent.close();

        return body;
    }


    public  String encrypt( String str, String publicKey ) throws Exception{

        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }


    /**
     * @description:  接收商户、商品信息
     * @name pushBussinessInfo
     * @author: xhj
     * @date: 2021/6/18 11:35
     * @version V1.0
     */
    @ApiOperation("接收浙食链数据")
    @PostMapping("/pushBusinessInfo")
    public ResultEx pushBusinessInfo(@RequestBody BusinessPushSo businessPushSo) {
        try {
            //获取商品信息
            List<GoodsInfo> list = businessPushSo.getGoods();
            //校验商品是否存在
            boolean goodsFlag=businessService.checkGoodsInfo(list);
            if(goodsFlag) {
                goodsInfoService.saveGoodsInfo(list);
            }
        }catch (Exception e){
            logger.error("商品信息获取失败",e);
            return ResultEx.builder().makeFailedResult("推送失败");

        }
        return ResultEx.builder().makeSuccessResult("推送成功");

    }

    /**
     * @description:  查询商户信息
     * @name businessInfo
     * @author: xhj
     * @date: 2021/6/18 11:35
     * @version V1.0
     */
    @ApiOperation("查询商户信息")
    @GetMapping("businessInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uniscId", value = "统一社会信用代码", defaultValue = ""),
            @ApiImplicitParam(name = "goodsId", value = "商品id", defaultValue = ""),
    })
    public ResultEx getBusinessInfo(BusinessPushSo businessPushSo) {
        try {
            return businessService.getBusinessInfo(businessPushSo);
        }catch (Exception e){
            logger.error("商户信息获取失败",e);
            return ResultEx.builder().makeFailedResult("商户信息获取失败");

        }
    }

    /**
     * @description:  查询台农链商品明细
     * @name goodsInfo
     * @author: xhj
     * @date: 2021/6/18 11:35
     * @version V1.0
     */
    @ApiOperation("查询台农链商品明细")
    @GetMapping("goodsInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品id", defaultValue = ""),
            @ApiImplicitParam(name = "uniscId", value = "统一信用代码", defaultValue = ""),
            @ApiImplicitParam(name = "batchInfo", value = "批次信息", defaultValue = ""),
            @ApiImplicitParam(name = " id-主体ID," +
                    "uniscId-统一信用代码," +
                    "businessName-主体名称," +
                    "scale-生产规模," +
                    "leadingProduct-主导产品" +
                    ",weight-重量," +
                    "pickTime-采摘日期 ," +
                    "authType-认证类别," +
                    "number-认证编号," +
                    "yield-批准产量," +
                    "termTime-有效期," +
                    "url-检测图片," +
                    "oType-操作类型," +
                    "pName-产品名称," +
                    "inThing-投入品," +
                    "oTime-操作时间 ",dataType = "string", defaultValue = "")

    })
    public ResultEx getGoodsInfo(GoodsInfo goodsInfo) {
        System.out.println("-----------goodsInfo---------------商品："+goodsInfo.getGoodsId()+"统一信用代码:"+goodsInfo.getUniscId()+"批次信息:"+goodsInfo.getBatchInfo());
        try {
            //保存访问记录
            VisitRecords visitRecords=VisitRecords.builder().property(0).visitTime(LocalDateTime.now()).build();
            visitRecordsService.save(visitRecords);
            return goodsInfoService.getGoodsInfo(goodsInfo);
        }catch (Exception e){
            logger.error("查询台农链商品明细信息获取失败",e);
            return ResultEx.builder().makeFailedResult("查询台农链商品明细信息获取失败");

        }
    }

    /**
     * @description:  查询台渔链商品明细
     * @name goodsInfo
     * @author: xhj
     * @date: 2021/6/18 11:35
     * @version V1.0
     */
    @ApiOperation("查询台渔链商品明细")
    @GetMapping("fishInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品id", defaultValue = ""),
            @ApiImplicitParam(name = "uniscId", value = "统一信用代码", defaultValue = ""),
            @ApiImplicitParam(name = "batchInfo", value = "批次信息", defaultValue = ""),
    })
    public ResultEx getFishGoodsInfo(GoodsInfo goodsInfo) {
        System.out.println("=----------fishInfo----------------商品："+goodsInfo.getGoodsId()+"统一信用代码:"+goodsInfo.getUniscId()+"批次信息:"+goodsInfo.getBatchInfo());
        try {
            //保存访问记录
            VisitRecords visitRecords=VisitRecords.builder().property(1).visitTime(LocalDateTime.now()).build();
            visitRecordsService.save(visitRecords);
            return goodsInfoService.getFishGoodsInfo(goodsInfo);
        }catch (Exception e){
            logger.error("查询台渔链商品明细信息获取失败",e);
            return ResultEx.builder().makeFailedResult("查询台渔链商品明细信息获取失败");

        }
    }

    /**
     * @description:  查询台渔链商品明细
     * @name goodsInfo
     * @author: xhj
     * @date: 2021/6/18 11:35
     * @version V1.0
     */
    @ApiOperation("查询台渔链商品明细-Ocale数据库")
    @GetMapping("fishDetails")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品id", defaultValue = ""),
            @ApiImplicitParam(name = "uniscId", value = "统一信用代码", defaultValue = ""),
            @ApiImplicitParam(name = "batchInfo", value = "批次信息", defaultValue = ""),
    })
    public JSONObject getFishDetails(String goodsId, String uniscId, String batchInfo) {
        System.out.println("-----------fishDetails---------------商品："+goodsId+"统一信用代码:"+uniscId+"批次信息:"+batchInfo);
        GoodsInfo goodsInfo = goodsInfoService.getBoatDetail( goodsId,  uniscId,  batchInfo);
        if(goodsInfo == null ){
            return new JSONObject();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String tradeTime=sdf.format(new Date(Long.valueOf(goodsInfo.getTradeTime())));
        String sql="  SELECT ZYYQ as NAME ,ZYLX,SYLX,BLSJ,YHSL FROM BIZ_1000_YHWSY  WHERE  YHZL = '海鳗' \n";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        Map<String , Object> map = new HashMap<>();
        map.put("data",list);
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(map));
        data.put("retCode",200);
        data.put("retMsg","成功");
        return data;

    }

}
